#!/bin/bash

win="$(xdotool getwindowfocus)" # we want this as early as possible, in case user switches window focus during execution

# dependency checks
for dep in xclip markdown sed perl; do
    type -f $dep >/dev/null || exit 1
done
perl -MHTML::Entities -e 1 || exit 1

# I use discount for a markdown executable. YMMV
md_opts="links,image,html,del,autolink,safelink,fencedcode,githubtags,nopants"

# keep adding expressions for all possible tags
expr="
s#<p>##g
s#</p>##g
s#<h.>#[h]#g
s#</h.>#[/h]#g
s#<blockquote>#[quote]#g
s#</blockquote>#[/quote]#g
s#<code>#[code]#g
s#</code>#[/code]#g
s#<ul>#[list]#g
s#</ul>#[/list]#g
s#<ol>#[list=1]#g
s#</ol>#[/list]#g
s#<li>#[*]#g
s#</li>##g
s#<a href=\([^>]*\)>#[url=\1]#g
s#</a>#[/url]#g
s#<pre>##g
s#</pre>##g
s#<em>#[i]#g
s#</em>#[/i]#g
s#<i>#[i]#g
s#</i>#[/i]#g
s#<b>#[b]#g
s#</b>#[/b]#g
s#<br>##g
s#<br/>##g
s#<del>#[strike]#g
s#</del>#[/strike]#g
s#<strong>#[b]#g
s#</strong>#[/b]#g
"

# let's use stderr (2) as the file descriptor to check for terminal
[ -t 2 ] && text="$(</dev/stdin)" || text="$(xclip -o)"

# The second sed expression compresses multiple empty lines into one
text="$(echo "$text" | markdown -f "$md_opts" | sed -e "$expr" -e 'N;/^\n$/D;P;D;' | perl -CS -MHTML::Entities -pe 'decode_entities($_);')"
# don't put closing tags on a separate line:
text="${text//$'\n'[\//[\/}"

[ -t 2 ] && echo "$text" && exit

echo "$text" | xclip -selection clipboard
xdotool key --clearmodifiers --window "$win" ctrl+v

exit 0
